/*
Rilego - An easy Images 2 E-Book converter.
Copyright (C) 2011  Federico Improta (Kirys)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package it.kirys.rilego.engine.loaders;

import it.kirys.rilego.engine.loaders.imagesources.IImageSource;
import it.kirys.rilego.engine.loaders.imagesources.ImageType;
import it.kirys.rilego.engine.loaders.imagesources.ZipImageSource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 *
 * @author Federico Improta
 */
public class ZipPackageLoader extends AbstractLoader {

	File packageFile;
	ZipFile zipFile;

	public BufferedInputStream getEntryStream(ZipEntry entry) throws IOException{
		return new BufferedInputStream(zipFile.getInputStream(entry));
	}//public BufferedInputStream getEntryStream(ZipEntry entry)

	@Override
	public String getIdentifier() {
		return zipFile.getName();
	}//public String getIdentifier()

	@Override
	public String generateSourceFullIdentifier(IImageSource source) {
		return getIdentifier().concat("#").concat(source.getIdentifier());
	}//public String generateSourceFullIdentifier(IImageSource source)


	private void parsePackage() throws IOException {
		zipFile = new ZipFile(packageFile);
		Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
		while (entries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			if (!entry.isDirectory() && ImageType.isKnown(entry.getName())) {
				ZipImageSource zis = new ZipImageSource(entry, this, ImageType.getFromFileName(entry.getName()));
				sources.add(zis);
			}
		}
	}//private void parsePackage() throws IOException

	public ZipPackageLoader(File packageFile) throws IOException {
		super();
		this.packageFile = packageFile;
		parsePackage();
	}//public ZipPackageLoader(File packageFile) throws IOException
}
